import axios from 'axios';
import { MessageBox, Message } from 'element-ui';
import Cookies from 'js-cookie';
import {getEnv} from "./browser";

let firstResponce = true;
// create an axios instance
const service = axios.create({
  baseURL: '', // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  headers: {
    'Content-Type': 'application/json;charset=utf-8',
  },
  timeout: 120000, // request timeout
});

export const getRequest = (appId, requestId) => `/p/webapi/request/${appId}/${requestId}`;

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    // if (process.env.NODE_ENV === 'development') {
    //   config.baseURL = (config.mock === true ? (process.env.VUE_APP_MOCK_API || '') : '') + config.baseURL;
    // }
    console.log(config);
    if (config.auth) {
      if (!config.data) {
        config.data = {};
      }
      
      config.data.token = getEnv().includes('pc') ? Cookies.get('index_token') : Cookies.get('mobile_token')
      if(process.env.NODE_ENV === 'development'){
          config.data.token = "0Z1Z6K90yJGMB_Re98MdvZXojgO4QIdEBBX0-6jIZ7G845kfY0AMOIzRnHbLe4Oaph5ebg-QBd4m1N1gw6KD5fC6oDc-xL8t_MYQ"
      }
      // console.log('config.data----------------',config.data)
    }
    return config;
  },
  error => {
    // do something with request error
    console.log(error); // for debug
    return Promise.reject(error);
  },
);

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data;
    console.log('响应结果----', res)
    const showAuthConfirm = !firstResponce;
    firstResponce = false;
    if (res.errorCode && res.errorCode !== "0") {
      // 处理导出
      if (res instanceof Blob) {
        return res;
      }
      if (res.errorCode === 100004) {
        localStorage.removeItem('token');
      }
      if (res.errorMessage && !res.msg) {
        try {
          const msg = JSON.parse(res.errorMessage)[0] || (`系统错误：${res.errorCode}`);
          res.msg = msg;
        } catch (e) {
          console.error(e);
        }
      }
      if (res.errorCode !== 100004 && res.errorCode !== 100016) {
        Message({
          message: res.msg,
          type: 'error',
          duration: 5 * 1000,
        });
      }
      console.log('错误结果',res);
      // Message.error(res.message)
      return Promise.reject(res);
    }
    return res.data;
  },
  error => {
    console.error(`err${error}`); // for debug
    Message({
      message: error.message||'请求出错,请稍后',
      type: 'error',
      duration: 5 * 1000,
    });
    return Promise.reject(error);
  },
);

export default service;
